############################################################################
############################################################################
####Non-state Atrocities in Capital Cities - Mechanism 2 (Correlations) ####
############################################################################
############################################################################
library(foreign)
library(doBy)
library(plyr)
library(DataCombine)
library(ggplot2)
library(ggthemes)

# Set working library
setwd("~/Data/Mechanism 2/")
# Read in data for plotting
m.dat.b <- read.dta("mech2analfull.dta")

############################
###All Civil Disobedience###
############################
#Correlations
cor(m.dat.b$camp, m.dat.b$lagincidentnonstatefull)
#Trendline
lm.pred <- lm(camp ~ lagincidentnonstatefull, data=m.dat.b)
#Confidence intervals
pp.pred <- predict(lm.pred)
V <- vcov(lm.pred)
X <- model.matrix(~ lagincidentnonstatefull, data=m.dat.b)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
predframe <- with(m.dat.b, data.frame(lagincidentnonstatefull,
                                      camp=pp.pred,lwr=pp.pred-1.96*se.fit,upr=pp.pred+1.96*se.fit))
#Limit sample to plotting only predictions maxed at 1
predframe <- subset(predframe, camp<=1.2)

p <- ggplot(m.dat.b, aes(x = lagincidentnonstatefull, y = camp))
pdf("cdins.pdf")
p +  labs(x="Number of Insurgent Atrocities", y="Ongoing Civil Disobedience") +
  geom_point()+ coord_cartesian(ylim=c(-0.05, 1.1), xlim=c(-0.05, 120), expand=F) +
  scale_y_discrete(limits=c(0, 1)) +
  annotate("text", x = 70, y = 0.75, label = "Correlation = 0.37") +
  geom_line(data=predframe, size=0.5, color="green") +
  geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3)
dev.off()

#######################################
###Remove Violent Civil Disobedience###
#######################################
# Subset the data
m.dat.c <- subset(m.dat.b, nvlcamp<2)
#Correlations
cor(m.dat.c$camp, m.dat.c$lagincidentnonstatefull)
#Trendline
lm.pred <- lm(camp ~ lagincidentnonstatefull, data=m.dat.c)
#Confidence intervals
pp.pred <- predict(lm.pred)
V <- vcov(lm.pred)
X <- model.matrix(~ lagincidentnonstatefull, data=m.dat.c)
se.fit <- sqrt(diag(X %*% V %*% t(X)))
predframe <- with(m.dat.c, data.frame(lagincidentnonstatefull,
                                      camp=pp.pred,lwr=pp.pred-1.96*se.fit,upr=pp.pred+1.96*se.fit))

p <- ggplot(m.dat.c, aes(x = lagincidentnonstatefull, y = camp))
pdf("cdinsnv.pdf")
p +  labs(x="Number of Insurgent Atrocities", y="Ongoing Nonviolent Civil Disobedience") +
  geom_point()+ coord_cartesian(ylim=c(-0.05, 1.1), xlim=c(-0.05, 22.5), expand=F) +
  scale_y_discrete(limits=c(0, 1)) +
  annotate("text", x = 12, y = 0.75, label = "Correlation = 0.12") +
  geom_line(data=predframe, size=0.5, color="green") +
  geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3)
dev.off()

